<template>
	<view class="object_page" :style="{ 'padding-bottom': pageType == 2 ? '30rpx' : '' }">
		<!-- 教师端 -->
		<view class="teacher">
			<view v-if="taskType!==0" class="more_checked">
				<view class="label" @click="handleAllCheck">
					<image v-if="checkedAllBtn" class="checked" src="@/static/iconPicture/checked.png" mode="">
					</image>
					<text v-else :class="{checkbox:true,'disabled_check':noFinishNum===0&&pageType==1}"></text>
				</view>
				<text :class="{ all: true, all_checked: checkedAllBtn }">{{pageType == 1 ? "全部完成" : "全选" }}</text>
			</view>
			<view :class="{ tab_fixed: fixedTab}">
				<RankTypeTab :tabsList="classList" :showSort="false" :activeIndex="activeClassId"
					@tapFilterType="tapFilterClass" />
			</view>
			<!-- 任务完成状态过滤 -->
			<view v-if="pageType==1" class="status_list">
				<view :class="{status_item:true,'active_status':i.status===activeStatus}"
					v-for="(i,idx) in taskStatusOpt" :key="idx" @click="filterStatus(i)">
					<text>{{i.text}}</text>
					<image class="active_icon" src="@/static/tabs/xia.png" v-show="i.status===activeStatus" mode="">
					</image>
				</view>
			</view>
			<view v-if="pageStatus === 'empty'" class="empty">
				<status-page :status="pageStatus" customEmptyText="暂无内容" :fixed="false"></status-page>
			</view>
			<view v-else class="send_object">
				<template v-if="taskType!==0">
					<view v-if="taskStatusInfo.status!==1">
						<template v-for="(i,idx) in classList" :key="idx">
							<view v-if="activeClassId===idx" class="class_more_checked">
								<view class="label" @click="handleAllClassCheck">
									<image v-if="i.checked" class="checked" src="@/static/iconPicture/checked.png"
										mode="">
									</image>
									<text v-else class="checkbox"></text>
								</view>
								<text
									:class="{ all: true, all_checked:i.checked }">{{pageType == 1 ? "本班完成" : "全选本班"}}</text>
							</view>
						</template>
					</view>
				</template>
				<view class="object_item" v-for="(i, idx) in classStudentList" :key="idx">
					<view class="left">
						<template v-if="taskType!==0">
							<view v-if="i.status!==1" class="label" @click="handleSingleCheck(i)">
								<image v-if="i.checked" class="checked" src="@/static/iconPicture/checked.png" mode="">
								</image>
								<text v-else class="checkbox"></text>
							</view>
						</template>
						<view class="name">{{ i.stuName }}</view>
					</view>
				</view>
			</view>
		</view>
		<view v-if="pageType == 2" class="footer">
			<button class="cancel" @click="handleCancel">取消</button>
			<button class="confirm" @click="handleConfirm">确认</button>
		</view>

		<CustomPopup titleText="完成提示" v-model="showFinishPopup" @handleConfirmBtn="handleConfirmFinish"
			@handleCancelBtn="handleCancelFinish">
			<view class="popup_box">是否确认完成？</view>
		</CustomPopup>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from "vue";
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import {
		useUserStore
	} from "@/store";
	import {
		staffStudentsListApi,
		getStaffTaskStuApi,
		updateTaskStatusApi
	} from "@/api";
	import RankTypeTab from "@/pages/subpackage/home/Components/RankTypeTab/RankTypeTab.vue";
	import CustomPopup from "@/pages/subpackage/home/Components/CustomPopup/CustomPopup.vue";
	const userStore = useUserStore();

	const pageStatus = ref('')
	const taskType = ref() // 任务类型 0-系统任务 1-自定义任务
	const taskStatusOpt = ref([{
		status: 0,
		text: '进行中'
	}, {
		status: 1,
		text: '已完成'
	}])
	const activeStatus = ref(0)
	const taskStatusInfo = ref({
		taskId: '',
		status: 0
	})

	const fixedTab = ref(false); //吸顶
	const activeClassId = ref(0) // 选中班级下标
	const checkedAllBtn = ref(false) // 全选

	const checkedList = ref([]); // 选中值

	const pageType = ref(); // 1查看 2编辑
	const classList = ref([]); // 教师管理班级
	const classStudentList = ref([]); // 班级学生
	const studentsTotal = ref(0) // 所有学生数
	const noFinishNum = ref(0) // 未完成学生数量

	const showFinishPopup = ref(false)

	// 全选
	function handleAllCheck() {
		if (pageType.value == 1) {
			if (noFinishNum.value === 0) return
			checkedAllBtn.value = !checkedAllBtn.value
			showFinishPopup.value = checkedAllBtn.value
			for (let i in classList.value) {
				classList.value[i].num = classList.value[i].stuList.filter(obj => obj.status !== 0).length
				classList.value[i].checked = classList.value[i].num !== classList.value[i].stuList.length // 本班没有全部勾选
				classList.value[i].stuList = classList.value[i].stuList.map(item => {
					return {
						...item,
						checked: item.status === 0 && checkedAllBtn.value
					}
				})
				for (let o in classList.value[i].stuList) {
					if (classList.value[i].stuList[o].checked) {
						checkedList.value.push(classList.value[i].stuList[o].stuId);
					}
				}
			}
		} else {
			checkedAllBtn.value = !checkedAllBtn.value
			for (let i in classList.value) {
				classList.value[i].checked = checkedAllBtn.value
				classList.value[i].stuList = classList.value[i].stuList.map(item => {
					return {
						...item,
						checked: checkedAllBtn.value
					}
				})
				if (checkedAllBtn.value) {
					for (let o in classList.value[i].stuList) {
						if (!checkedList.value.includes(classList.value[i].stuList[o].stuId)) {
							checkedList.value.push(classList.value[i].stuList[o].stuId);
						}
					}
				} else {
					for (let o in classList.value[i].stuList) {
						checkedList.value.splice(checkedList.value.indexOf(classList.value[i].stuList[o].stuId), 1);
					}
				}
			}
		}
		classStudentList.value = classList.value[activeClassId.value].stuList
	}
	// 全选班级
	function handleAllClassCheck() {
		if (pageType.value == 1) {
			showFinishPopup.value = true
			classList.value[activeClassId.value].checked = !classList.value[activeClassId.value].checked
			for (let i in classStudentList.value) {
				classStudentList.value[i] = {
					...classStudentList.value[i],
					checked: classList.value[activeClassId.value].checked
				}
				if (classStudentList.value[i].checked) {
					checkedList.value.push(classStudentList.value[i].stuId);
				}
			}

		} else {
			classList.value[activeClassId.value].checked = !classList.value[activeClassId.value].checked
			classStudentList.value = classStudentList.value.map(item => {
				return {
					...item,
					checked: classList.value[activeClassId.value].checked
				}
			})
			if (classList.value[activeClassId.value].checked) {
				for (let i in classStudentList.value) {
					if (!checkedList.value.includes(classStudentList.value[i].stuId)) {
						checkedList.value.push(classStudentList.value[i].stuId);
					}
				}
			} else {
				for (let i in classStudentList.value) {
					checkedList.value.splice(checkedList.value.indexOf(classStudentList.value[i].stuId), 1);
				}
			}
			checkedAllBtn.value = studentsTotal.value === checkedList.value.length
		}

	}
	// 单选
	function handleSingleCheck(i) {
		if (pageType.value == 1) {
			showFinishPopup.value = true
		}
		i.checked = !i.checked;
		let classStudentsTotal = classStudentList.value.length
		let checkedTotal = classStudentList.value.filter(item => item.checked).length
		classList.value[activeClassId.value].checked = classStudentsTotal === checkedTotal
		if (i.checked) {
			checkedList.value.push(i.stuId);
		} else {
			checkedList.value.splice(checkedList.value.indexOf(i.stuId), 1);
		}
		checkedAllBtn.value = studentsTotal.value === checkedList.value.length
	}

	// 过滤类型
	function tapFilterClass(e) {
		activeClassId.value = classList.value.findIndex(
			(item) => item.classId === e.classId
		)
		let filterClass = classList.value[activeClassId.value]
		classStudentList.value = filterClass.stuList.map(item => {
			if (filterClass.checked) {
				return {
					...item,
					checked: filterClass.checked
				}
			} else {
				return {
					...item,
					checked: checkedList.value.includes(item.stuId)
				}
			}
		})
		pageStatus.value = classStudentList.value.length === 0 ? 'empty' : ''
	}
	// 完成状态过滤
	function filterStatus(i) {
		taskStatusInfo.value.status = i.status
		activeStatus.value = i.status
		fetchStudentMailStatus()

	}
	// 当前班级是否全勾选
	function count(arr1, arr2) {
		let checked = false
		let total = arr2.length
		const sameTotal = arr2.filter(obj =>
			arr1.some(value => obj.stuId === value)
		).length
		return checked = total === sameTotal

	}
	// 获取教师管理的班级
	async function fetchClassInfo() {
		studentsTotal.value = 0
		classList.value = [];
		uni.showLoading({
			title: "加载中...",
		});
		let res = await staffStudentsListApi();
		if (res.code === 200) {
			let data = res.data
			for (let i in data) {
				classList.value.push({
					classId: data[i].classId,
					dictLabel: data[i].className,
					stuList: data[i].stuList.map(item => {
						return {
							...item,
							checked: checkedList.value.includes(item.stuId)
						}
					}),
					checked: count(checkedList.value, data[i].stuList),

				});
				studentsTotal.value += data[i].stuList.length
			}
			checkedAllBtn.value = studentsTotal.value === checkedList.value.length
			classStudentList.value = classList.value[activeClassId.value].stuList;
		}
		uni.hideLoading();
	}
	// 学生未完成完成数量
	function finishCount(arr) {
		let total = arr.filter(obj => obj.status === 0).length
		noFinishNum.value += total

	}
	// 教师学生任务情况
	async function fetchStudentMailStatus() {
		studentsTotal.value = 0
		noFinishNum.value = 0
		classList.value = [];
		checkedAllBtn.value = false
		uni.showLoading({
			title: '加载中...'
		})
		let res = await getStaffTaskStuApi({
			...taskStatusInfo.value
		})
		uni.hideLoading()
		if (res.code === 200) {
			let data = res.data
			for (let i in data) {
				classList.value.push({
					classId: data[i].classId,
					dictLabel: data[i].className,
					stuList: data[i].stuList.map(item => {
						return {
							...item,
							checked: false,
						}
					}),
					checked: false,
				});
				finishCount(data[i].stuList)
				studentsTotal.value += data[i].stuList.length
			}
			classStudentList.value = classList.value[activeClassId.value].stuList;
			pageStatus.value = classStudentList.value.length === 0 ? 'empty' : ''
		}
	}
	// 确认
	function handleConfirm() {
		uni.$emit("updateTaskSendObject", {
			list: JSON.stringify(checkedList.value),
		});
		uni.navigateBack();
	}
	// 取消
	function handleCancel() {
		checkedList.value = [];
		uni.navigateBack();
	}
	// 确认完成
	async function handleConfirmFinish() {

		taskStatusInfo.value.status = 1
		uni.showLoading({
			title: '正在完成...'
		})
		let res = await updateTaskStatusApi({
			...taskStatusInfo.value,
			stuIdList: checkedList.value
		})
		uni.hideLoading()
		if (res.code === 200) {
			uni.showToast({
				icon: 'none',
				title: '已完成'
			})
			taskStatusInfo.value.status = 0
			fetchStudentMailStatus()
			showFinishPopup.value = false
		}
	}
	// 取消完成
	function handleCancelFinish() {
		checkedList.value = []
		checkedAllBtn.value = false
		for (let i in classList.value) {
			classList.value[i].checked = checkedAllBtn.value
			classList.value[i].stuList = classList.value[i].stuList.map(item => {
				return {
					...item,
					checked: checkedAllBtn.value
				}
			})
		}
		classStudentList.value = classList.value[activeClassId.value].stuList
	}
	// 吸顶
	function handleFixed() {
		const observer = uni.createIntersectionObserver(this);
		observer.relativeToViewport().observe(".teacher", (res) => {
			if (res.intersectionRatio > 0) {
				fixedTab.value = false;
			} else {
				fixedTab.value = true;
			}
		});
	}
	onMounted(() => {
		handleFixed();
	});

	onLoad((option) => {
		pageType.value = option.pageType;
		uni.setNavigationBarTitle({
			title: pageType.value == 1 ? "发送对象" : "选择发送对象",
		});
		if (pageType.value == 1) {
			// 查看
			let details = JSON.parse(decodeURIComponent(option.details))
			taskType.value = details.customTask
			taskStatusInfo.value.taskId = details.id
			fetchStudentMailStatus()
		} else {
			checkedList.value = JSON.parse(option.checkedList)
			fetchClassInfo();
		}
	});
</script>

<style lang="scss" scoped>
	.object_page {
		.patriarch {
			margin: 30rpx 0;
		}

		.teacher {
			.tab_fixed {
				position: fixed;
				top: 0;
				z-index: 1;
			}

			.more_checked {
				display: flex;
				align-items: center;
				padding: 20rpx 30rpx 24rpx 30rpx;
				background-color: #fff;
				box-sizing: border-box;

				.tip_icon {
					width: 30rpx;
					height: 30rpx;


				}
			}

			.all {
				display: block;
				margin: 0 8rpx 0 8rpx;
				color: #333;
				font-size: 30rpx;
				font-weight: 500;
			}

			.all_checked {
				color: #615dff;
			}

			.status_list {
				height: 110rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				background-color: #fff;

				.status_item {
					display: inline-block;
					padding: 12rpx 18rpx;
					border-radius: 10rpx;
					background-color: #F9F9FB;
					color: #333333;
					font-size: 30rpx;
					line-height: 42rpx;

					&:first-child {
						margin-right: 100rpx;
					}
				}

				.active_status {
					position: relative;
					background-color: #615DFF;
					color: #FFFFFF;

					.active_icon {
						position: absolute;
						bottom: -14rpx;
						left: 50%;
						transform: translateX(-50%);
						width: 35rpx;
						height: 20rpx;
					}
				}
			}

			.class_more_checked {
				display: flex;
				align-items: center;
				padding: 30rpx 0 0 0;
			}
		}

		.label {
			width: 30rpx;
			height: 30rpx;
			margin-right: 16rpx;


			.checkbox {
				display: block;
				width: 100%;
				height: 100%;
				border-radius: 6rpx;
				border: 1rpx solid #ddd;
				box-sizing: border-box;
			}

			.checked {
				display: block;
				width: 100%;
				height: 100%;

			}

			.disabled_check {
				background-color: #f9f9fb;
			}
		}

		.empty {
			height: calc(100vh - 292rpx);
		}

		.send_object {
			margin-top: 16rpx;
			padding: 0 30rpx;
			background-color: #fff;


			.tip {
				display: flex;
				justify-content: flex-end;
				padding-top: 30rpx;

				&_icon {
					width: 30rpx;
					height: 30rpx;
				}
			}

			.object_item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 36rpx 0;
				border-bottom: 1rpx solid #eeeeee;
				box-sizing: border-box;
				color: #333;
				font-size: 30rpx;

				&:last-child {
					border-bottom: none;
				}

				.left {
					display: flex;
					align-items: center;
				}

				.right {
					font-size: 30rpx;

					.revocation {
						margin-right: 16rpx;
						color: #ff2828;
					}

					.unread {
						color: #615dff;
					}

					.been {
						color: #a9aab5;
					}
				}

				.name {
					line-height: 42rpx;
				}
			}
		}

		.footer {
			display: flex;
			position: fixed;
			bottom: 0;
			left: 0;
			padding: 16rpx 0 0 0;
			width: 100%;
			height: 172rpx;
			box-sizing: border-box;
			background-color: #fff;
			border-top: 1rpx solid #eee;

			button::after {
				border: none;
			}

			.cancel {
				width: 230rpx;
				height: 90rpx;
				color: #615dff;
				background-color: #ececff;
			}

			.confirm {
				margin-left: 20rpx;
				height: 90rpx;
				width: 440rpx;
				color: #fff;
				background-color: #615dff;
			}
		}

		.popup_box {
			margin: 50rpx 0;
			box-sizing: border-box;
		}
	}
</style>